# -*- coding: utf-8 -*-
# @Author: felix
import copy

import pytest
import allure
from apiAtRun.parse.YamlCaseParser import yaml_Op
from apiAtRun.extend.keywords import KeyWords
from apiAtRun.core.globalContext import g_context
from apiAtRun.utils.VarRender import t_refresh
from apiAtRun.utils.DynamicTitle import dynamicTitle
from apiAtRun.parse.CaseParser import case_parser

"""
核心执行器

"""



class TestRunner:
    # TODO 1, 读取测试用例数据
    # case_Info = case_parser("excel","\\example")




    # TODO 2, 进行参数化
    # @pytest.mark.parametrize("caseInfo", case_Info.get("case_infos"))
    def test_case_exeute(self,caseInfo):
        print("当前测试数据:",caseInfo)
        # 动态生成用例标题
        #allure.dynamic.title(caseInfo["_case_name"])

        dynamicTitle(caseInfo)



        # TODO 2 -1, 基于Yaml中的步骤，一步一步进行执行
        try:

            # TODO 扩展DDT- 获取单用例范围内的 变量数据.方面后续的渲染 --将ddt中的测试用例数据写到全局变量中，进行渲染
            local_context = caseInfo.get("context", {})
            context = copy.deepcopy(g_context().show_dict())
            context.update(local_context)



            # TODO 3: 实例化对象
            keywords = KeyWords()
            # TODO 4: 获取对应的步骤，然后进行遍历
            steps = caseInfo.get("steps", None)
            print("获取的步骤:",steps)
            for step in steps:
                # 提示信息
                print("获取的key:", list(step.keys()))
                print("获取的value:", list(step.values()))
                step_name = list(step.keys())[0]
                step_value = list(step.values())[0]
                print(f"开始执行步骤：{step_name} - {step_value}")

                # TODO 扩展-变量渲染
                context = copy.deepcopy(g_context().show_dict())    # 使用深拷贝，获取全局变量

                # TODO 扩展DDT - 把当前用例也更新进去
                context.update(local_context)

                step_value = eval(t_refresh(step_value, context))  # 全局变量+用例变量渲染

                with allure.step(step_name):
                    key = step_value["关键字"]
                    try:
                        # TODO 5: 通过反射的方法拿到对应的方法
                        key_func = keywords.__getattribute__(key)
                    except AttributeError as e:
                        print("没有这个关键字：", e)
                    key_func(**step_value)  # 调用关键字方法
        finally:
            print("---执行当前用例结束---")

